/*
 * Copyright (C) 2009 aileron.cc
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package cc.aileron.mail.daemon;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;

import cc.aileron.mail.MailSetting;
import cc.aileron.mail.MailetApplication;
import cc.aileron.mail.MailetDaemon;

import com.google.inject.Inject;
import com.google.inject.Singleton;

/**
 * @author Aileron
 */
@Singleton
public class MailetDaemonImpl implements MailetDaemon
{
    @Override
    public Void call() throws Exception
    {
        folder.open(Folder.READ_WRITE);
        while (isActive)
        {

            final int unredCount = folder.getUnreadMessageCount();
            if (unredCount > 0)
            {
                for (final Message message : folder.getMessages())
                {
                    application.execute(message);
                }
            }
            Thread.sleep(100);
        }
        if (folder.isOpen())
        {
            folder.close(false);
        }
        return null;
    }

    /**
     * @param setting
     * @param application
     * @throws MessagingException
     */
    @Inject
    public MailetDaemonImpl(
        final MailSetting setting,
        final MailetApplication application) throws MessagingException
    {
        this.application = application;
        final Session session = Session.getDefaultInstance(
                setting.properties(), null);
        final Store store = session.getStore(setting.type()
            .name()
            .toLowerCase());
        store.connect(setting.host(), setting.port(), setting.account(),
                setting.password());
        this.folder = store.getFolder(setting.folderName());
    }

    private final MailetApplication application;
    private final Folder folder;
    private volatile boolean isActive = true;
}
